package com.sendpo.zjx.sendpo.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.StoreMainAllProduceActivity;
import com.sendpo.zjx.sendpo.activity.WebOnlineContentActivity;
import com.sendpo.zjx.sendpo.domain.MerchantVideoDomain;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by zjx on 2018
 */

public class WatchStoreAllFragment extends BaseWatchStoreFragment implements AMapLocationListener {
    //    @BindView(R.id.dropDownMenu)
//    DropDownMenu dropDownMenu;
//    private View dropcontent = null;
//    public String[] headers = { "全部分类", "全城", "智能排序" };
//    public LinearLayoutManager layoutManager;
//    public String[] locationtype = { "全城", "地区", "本地" };
//    public String[] ordertype = { "智能排序", "时间排序", "评价排序" };
    @BindView(value = R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(value = R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;
    @BindView(R.id.city)
    TextView city_name;
    Unbinder unbinder;
    private int pagenow = 1;
    private String city = "";
    RecylcerMessageAdaper adaper;
    private View rootView;
    private double longlitude = 0;
    private double laltidude = 0;
    public LinearLayoutManager lm;
//    public String[] storetype = { "全部分类", "商品", "餐饮", "影视", "健康" };
//    public int[] types = { DropDownMenu.TYPE_LIST_SIMPLE, DropDownMenu.TYPE_LIST_SIMPLE, DropDownMenu.TYPE_LIST_CITY };

    @Override
    public View initView() {
        View localView = View.inflate(this.mActivity, R.layout.fragment_watchstore, null);
        ButterKnife.bind(localView, this.mActivity);
        return localView;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, rootView);
            initComponent();
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    public void initComponent() {
        lm = new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL, false);
        recyclerview.setLayoutManager(lm);
        List<MerchantVideoDomain.DataBean> dataBeans = new ArrayList<>();
        recyclerview.setAdapter(adaper = new RecylcerMessageAdaper(mActivity, dataBeans));
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                AmapLocationService amapLocationService = new AmapLocationService(mActivity);
                amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
                amapLocationService.registerListener(WatchStoreAllFragment.this);
                amapLocationService.start();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                pagenow++;
                initAppend(pagenow, city);
            }
        });
        AmapLocationService amapLocationService = new AmapLocationService(mActivity);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(WatchStoreAllFragment.this);
        amapLocationService.start();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null) {
            pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            return;
        }
        city = aMapLocation.getCity();
        city_name.setText(""+aMapLocation.getDistrict());
        longlitude = aMapLocation.getLongitude();
        laltidude = aMapLocation.getLatitude();
        pagenow = 1;
        initRefresh(pagenow, city);
    }


    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public class RecylcerMessageAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public LayoutInflater inflater;
        public List<MerchantVideoDomain.DataBean> dataBeans;

        public RecylcerMessageAdaper(Context context, List<MerchantVideoDomain.DataBean> dataBeans) {
            this.inflater = LayoutInflater.from(context);
            this.dataBeans = dataBeans;
        }

        public int getItemCount() {
            return this.dataBeans.size();
        }

        public void onBindViewHolder(RecyclerView.ViewHolder paramViewHolder, int paramInt) {
            IndexHoler ih = (IndexHoler) paramViewHolder;
            final MerchantVideoDomain.DataBean videoDomain = dataBeans.get(paramInt);

            ih.shopping_tv.setText("" + videoDomain.getMerchantsName());
            Glide.with(WatchStoreAllFragment.this.mActivity).load("" + videoDomain.getMerchantsImg()).asBitmap().animate(R.anim.fade_in).placeholder(R.color.default_lightgray).override(300, 300).into(ih.icon);
            ih.shexiangtou_iv.setOnClickListener(new View.OnClickListener() {
                public void onClick(View paramAnonymousView) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("data", videoDomain);
                    Tools.redirectActivity(WatchStoreAllFragment.this.mActivity, WebOnlineContentActivity.class, map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("merchantsId", videoDomain.getMerchantsId());
                    Tools.redirectActivity(mActivity, StoreMainAllProduceActivity.class, map);
                }
            });
            LatLng m_latLng = new LatLng(laltidude, longlitude);
            LatLng latLng = new LatLng(Double.parseDouble(videoDomain.getLatitude()), Double.parseDouble(videoDomain.getLongitude()));
            int distance = (int) AMapUtils.calculateLineDistance(m_latLng, latLng);
            if (distance == 0) {
                ih.locationsize_tv.setText("就在附近");
            } else if (distance <= 5) {
                ih.locationsize_tv.setText("不足5m");
            } else {
                if (distance >= 1000) {
                    ih.locationsize_tv.setText("距离" + (distance / 1000) + "km");
                } else {
                    ih.locationsize_tv.setText("距离" + distance + "m");
                }

            }
        }

        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup paramViewGroup, int paramInt) {
            return new IndexHoler(this.inflater.inflate(R.layout.layout_business_listitem, paramViewGroup, false));
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public ImageView icon;
            public TextView shopping_tv;
            public View rootView;
            public ImageView shexiangtou_iv;
            public TextView address;
            public TextView locationsize_tv;

            public IndexHoler(View itemView) {
                super(itemView);
                locationsize_tv = itemView.findViewById(R.id.locationsize_tv);
                address = itemView.findViewById(R.id.address);
                shopping_tv = itemView.findViewById(R.id.shopping_tv);
                this.rootView = itemView;
                this.shexiangtou_iv = itemView.findViewById(R.id.shexiangtou_iv);
                this.icon = itemView.findViewById(R.id.icon);
            }
        }

        public void initRefresh(List<MerchantVideoDomain.DataBean> domains) {
            this.dataBeans.removeAll(this.dataBeans);
            this.dataBeans.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchantVideoDomain.DataBean> domains) {
            this.dataBeans.addAll(domains);
            notifyDataSetChanged();
        }
    }

    public void initRefresh(int pagenow, String city) {
        Map<String, String> map = new HashMap<>();
        map.put("page", pagenow + "");
        map.put("pageSize", "10");
        map.put("city", "" + city);
        Xutils.GET(HttpUrl.getMerchantsVideo, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                MerchantVideoDomain dataBean = gson.fromJson(result, MerchantVideoDomain.class);
                if (dataBean.isFlag()) {
                    if (dataBean.getData() != null && dataBean.getData().size() != 0) {
                        if (adaper == null) {
                            adaper = new RecylcerMessageAdaper(mActivity, dataBean.getData());
                        } else {
                            adaper.initRefresh(dataBean.getData());
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void initAppend(int pagenow, String city) {
        Map<String, String> map = new HashMap<>();
        map.put("page", pagenow + "");
        map.put("pageSize", "10");
        map.put("city", "" + city);
        Xutils.GET(HttpUrl.getMerchantsVideo, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                MerchantVideoDomain dataBean = gson.fromJson(result, MerchantVideoDomain.class);
                if (dataBean.isFlag()) {
                    if (dataBean.getData() != null && dataBean.getData().size() != 0) {
                        if (adaper == null) {
                            adaper = new RecylcerMessageAdaper(mActivity, dataBean.getData());
                        } else {
                            adaper.initAppend(dataBean.getData());
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
